package com.xuhao.didi.oksocket;

import com.xuhao.didi.core.pojo.OriginalData;
import com.xuhao.didi.oksocket.adapter.LogAdapter;
import com.xuhao.didi.oksocket.btnview.Ripple;
import com.xuhao.didi.oksocket.data.AdminHandShakeBean;
import com.xuhao.didi.oksocket.data.AdminKickOfflineBean;
import com.xuhao.didi.oksocket.data.LogBean;
import com.xuhao.didi.oksocket.data.RestartBean;
import com.xuhao.didi.socket.client.impl.client.action.ActionDispatcher;
import com.xuhao.didi.socket.client.sdk.OkSocket;
import com.xuhao.didi.socket.client.sdk.client.ConnectionInfo;
import com.xuhao.didi.socket.client.sdk.client.OkSocketOptions;
import com.xuhao.didi.socket.client.sdk.client.action.SocketActionAdapter;
import com.xuhao.didi.socket.client.sdk.client.connection.IConnectionManager;
import com.xuhao.didi.socket.common.interfaces.utils.TextUtils;
import ohos.aafwk.ability.Ability;
import ohos.aafwk.content.Intent;
import ohos.agp.components.*;
import ohos.agp.components.element.ShapeElement;
import ohos.agp.utils.Color;
import ohos.eventhandler.EventHandler;
import ohos.eventhandler.EventRunner;
import ohos.miscservices.pasteboard.PasteData;
import ohos.miscservices.pasteboard.SystemPasteboard;

import java.nio.charset.Charset;

public class ServerAdmin extends Ability implements Component.ClickedListener, Component.FocusChangedListener {
    private ConnectionInfo mInfo;
    private TextField mIpEt;
    private TextField mPortEt;
    private IConnectionManager mManager;
    private OkSocketOptions mOkOptions;
    private Ripple mConnect;
    private Ripple mClearLog;
    private Ripple mRestart;
    private Ripple mKickOffLine;
    private Text mPortHint;
    private Text mPortText;
    private Text mEditHint;
    private Text mIpText;
    private ListContainer mOpsList;
    private String mPass;
    private TextUtile textUtils;
    private LogAdapter mReceLogAdapter;

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_server_admin);
        findViews();
        initData();
    }

    private void initData() {
        mReceLogAdapter = new LogAdapter(this);
        mOpsList.setItemProvider(mReceLogAdapter);
        initManager();
        mOpsList.setItemLongClickedListener(new ListContainer.ItemLongClickedListener() {
            @Override
            public boolean onItemLongClicked(ListContainer listContainer, Component component, int i, long l) {
                LogBean log = (LogBean) listContainer.getItemProvider().getItem(i);
                SystemPasteboard systemPasteboard = SystemPasteboard.getSystemPasteboard(ServerAdmin.this);
                PasteData pasteData = PasteData.creatPlainTextData(log.mWho == null ? "" : log.mWho);
                systemPasteboard.setPasteData(pasteData);
                TextUtile textUtile = new TextUtile();
                textUtile.toastText("复制到剪切板", ServerAdmin.this);
                return false;
            }
        });
    }

    private void initManager() {
        EventHandler mHandler = new EventHandler(EventRunner.getMainEventRunner());
        mInfo = new ConnectionInfo(mIpEt.getText(), Integer.parseInt(mPortEt.getText()));
        mOkOptions = new OkSocketOptions.Builder()
                .setConnectTimeoutSecond(10)
                .setCallbackThreadModeToken(new OkSocketOptions.ThreadModeToken() {
                    @Override
                    public void handleCallbackEvent(ActionDispatcher.ActionRunnable runnable) {
                        mHandler.postTask(runnable);
                    }
                }).build();
        mManager = OkSocket.open(mInfo).option(mOkOptions);
        mManager.registerReceiver(adapter);
    }

    private void findViews() {
        textUtils = new TextUtile();
        mOpsList = (ListContainer) findComponentById(ResourceTable.Id_ops_list);
        mIpEt = (TextField) findComponentById(ResourceTable.Id_ip);
        mKickOffLine = (Ripple) findComponentById(ResourceTable.Id_kick_people_offline);
        mPortEt = (TextField) findComponentById(ResourceTable.Id_port);
        mClearLog = (Ripple) findComponentById(ResourceTable.Id_clear_log);
        mConnect = (Ripple) findComponentById(ResourceTable.Id_connect);
        mRestart = (Ripple) findComponentById(ResourceTable.Id_restart);
        mEditHint = (Text) findComponentById(ResourceTable.Id_edit_hint);
        mIpText = (Text) findComponentById(ResourceTable.Id_ip_text);
        mPortHint = (Text) findComponentById(ResourceTable.Id_port_hint);
        mPortText = (Text) findComponentById(ResourceTable.Id_port_text);
        mConnect.setClickedListener(this);
        mClearLog.setClickedListener(this);
        mRestart.setClickedListener(this);
        mKickOffLine.setClickedListener(this);
        mIpEt.setFocusChangedListener(this);
        mPortEt.setFocusChangedListener(this);
        textField();
    }

    private void textField() {
        if (!TextUtils.isEmpty(mIpEt.getText())) {
            mEditHint.setVisibility(Component.VISIBLE);
            mIpText.setVisibility(Component.VERTICAL);
        } else {
            mEditHint.setVisibility(Component.VERTICAL);
            mIpText.setVisibility(Component.VISIBLE);
        }
        if (!TextUtils.isEmpty(mPortEt.getText())) {
            mPortHint.setVisibility(Component.VISIBLE);
            mPortText.setVisibility(Component.VERTICAL);
        } else {
            mPortHint.setVisibility(Component.VERTICAL);
            mPortText.setVisibility(Component.VISIBLE);
        }
    }

    private SocketActionAdapter adapter = new SocketActionAdapter() {
        @Override
        public void onSocketConnectionSuccess(ConnectionInfo info, String action) {
            AdminHandShakeBean adminHandShakeBean = new AdminHandShakeBean(mPass);
            mManager.send(adminHandShakeBean);
            mConnect.setText("DisConnect");
            log("连接成功");
            mPortEt.setEnabled(false);
            mIpEt.setEnabled(false);
            textUtils.chickColor(ServerAdmin.this,mIpEt,mPortEt);
            mIpEt.clearFocus();
            mPortEt.clearFocus();
        }

        @Override
        public void onSocketDisconnection(ConnectionInfo info, String action, Exception e) {
            if (e != null) {
                log("异常断开:" + e.getMessage());
            } else {
                log("正常断开");
            }
            mPortEt.setEnabled(true);
            mIpEt.setEnabled(true);
            mConnect.setText("Connect");
            textUtils.chickTextColor(ServerAdmin.this,mIpEt,mPortEt);
        }

        @Override
        public void onSocketConnectionFailed(ConnectionInfo info, String action, Exception e) {
            log("连接失败");
            mConnect.setText("Connect");
            mPortEt.setEnabled(true);
            mIpEt.setEnabled(true);
            textUtils.chickTextColor(ServerAdmin.this,mIpEt,mPortEt);
        }

        @Override
        public void onSocketReadResponse(ConnectionInfo info, String action, OriginalData data) {
            String str = new String(data.getBodyBytes(), Charset.forName("utf-8"));
            log(str);
        }
    };

    private void log(String log) {
        LogBean logBean = new LogBean(System.currentTimeMillis(), log);
        try {
            logBean.mWho = log.substring(0, log.indexOf("@"));
        } catch (Exception e) {
        }
        mReceLogAdapter.getDataList().add(0, logBean);
        mReceLogAdapter.notifyDataChanged();
    }

    @Override
    protected void onStop() {
        super.onStop();
        if (mManager != null) {
            mManager.disconnect();
            mManager.unRegisterReceiver(adapter);
        }
    }

    @Override
    public void onClick(Component component) {
        switch (component.getId()) {
            case ResourceTable.Id_connect:
                if (mManager == null) {
                    return;
                }
                if (!mManager.isConnect()) {
                    initManager();
                    textUtils.commonDialog(ServerAdmin.this, "Admin Login", "Admin Pass:", "CANCEL", "LOGIN");
                    textUtils.getCancel().setClickedListener(new Component.ClickedListener() {
                        @Override
                        public void onClick(Component component) {
                            mPass = textUtils.getText().getText();
                            mPortEt.setEnabled(false);
                            mIpEt.setEnabled(false);
                            textUtils.chickColor(ServerAdmin.this,mIpEt,mPortEt);
                            mManager.connect();
                            textUtils.getCommonDialog().destroy();
                        }
                    });
                } else {
                    mConnect.setText("DisConnecting");
                    mManager.disconnect();
                    textUtils.getCommonDialog().destroy();
                }
                break;
            case ResourceTable.Id_clear_log:
                mReceLogAdapter.getDataList().clear();
                mReceLogAdapter.notifyDataChanged();
                break;
            case ResourceTable.Id_restart:
                if (mManager == null) {
                    return;
                }
                if (!mManager.isConnect()) {
                    textUtils.toastText("请先连接!", ServerAdmin.this);
                } else {
                    mManager.send(new RestartBean());
                }
                break;
            case ResourceTable.Id_kick_people_offline:
                if (mManager == null) {
                    return;
                }
                if (!mManager.isConnect()) {
                    textUtils.toastText("请先连接!", ServerAdmin.this);
                } else {
                     textUtils.commonDialog(ServerAdmin.this, "Who:", "who:", "CANCEL", "DO IT");
                    textUtils.getCancel().setClickedListener(new Component.ClickedListener() {
                        @Override
                        public void onClick(Component component) {
                            String who = textUtils.getText().getText();
                            mManager.send(new AdminKickOfflineBean(who));
                            textUtils.getCommonDialog().destroy();
                        }
                    });
                }
                break;
            default:
                break;
        }
    }

    @Override
    public void onFocusChange(Component component, boolean isFocus) {
        ShapeElement errorElement;
        String color = "";
        switch (component.getId()) {
            case ResourceTable.Id_port:
                if (isFocus) {
                    color = "#169E93";
                    errorElement = new ShapeElement(this, ResourceTable.Graphic_background_textfild_color);
                    if (mPortText.getVisibility() == Component.VISIBLE) {
                        textUtils.animatorField(mPortText, true, 11);
                    }
                } else {
                    color = "#7A7A7A";
                    errorElement = new ShapeElement(this, ResourceTable.Graphic_background_textfild_uncolor);
                    textUtils.animatorField(mPortText, false, 15);
                }
                mPortHint.setHintColor(new Color(Color.getIntColor(color)));
                mPortText.setHintColor(new Color(Color.getIntColor(color)));
                mPortEt.setBasement(errorElement);
                break;
            case ResourceTable.Id_ip:
                if (isFocus) {
                    color = "#169E93";
                    errorElement = new ShapeElement(this, ResourceTable.Graphic_background_textfild_color);
                    if (mIpText.getVisibility() == Component.VISIBLE) {
                        textUtils.animatorField(mIpText, true, 11);
                    }
                } else {
                    color = "#7A7A7A";
                    errorElement = new ShapeElement(this, ResourceTable.Graphic_background_textfild_uncolor);
                    textUtils.animatorField(mIpText, false, 15);
                }
                mEditHint.setHintColor(new Color(Color.getIntColor(color)));
                mIpText.setHintColor(new Color(Color.getIntColor(color)));
                mIpEt.setBasement(errorElement);
                break;
            default:
                break;
        }
    }
}
